package com.xiaoq.matrix.activity.endpoint;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.RedisTemplate4JedisCluster;
import com.xiaoq.apis.sites.ISitesApi;
import com.xiaoq.apis.sites.SitesInfo4Activity;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.coms.util.JsonUtil;
import com.xiaoq.coms.util.MapUtil;
import com.xiaoq.matrix.activity.entity.ActivityAttendentEntity;
import com.xiaoq.matrix.activity.entity.ActivityEntity;
import com.xiaoq.matrix.activity.service.IActivityAttendService;
import com.xiaoq.matrix.activity.service.IActivityService;
import com.xiaoq.matrix.activity.vo.ActivityAttendVo;
import com.xiaoq.matrix.activity.vo.ActivityVo;
import com.xiaoq.matrix.vo.ContentStaticResponseVo;
import com.xiaoq.vo.PagingVo;
import com.xiaoq.web.HttpsRestTemplate;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/v1/activity")
public class ActivityEndpoint2B {

	@Autowired
	private IActivityAttendService activityAttendSer;

	@Autowired
	private IActivityService activitySer;
	
	@Autowired
	private IdGenerator idGenerator;
	
	@Reference(interfaceClass=ISitesApi.class,check=false,version="1.0.0")
	private ISitesApi sitesApi;
	
	@Autowired
	private RedisTemplate4JedisCluster redisTemplate;
	
	@Value("${yunyingAdress}")
	private String yunyingAdress;
	
	@Autowired
	private HttpsRestTemplate rest;

	private static final Logger LOG = LoggerFactory.getLogger(ActivityEndpoint2B.class);

	private class UserActivityAttendList extends GenericListResponse<ActivityAttendVo> {
	}

	private class ActivityDetailResponse extends GenericDataResponse<ActivityVo> {
	}

	private class ActivityPubResponse extends GenericDataResponse<String> {
	}

	private class ActivityListOrgnizer extends GenericListResponse<ActivityVo> {
	}


	@ApiOperation(value = "获取活动的报名信息列表", notes = "获取活动的报名信息列表")
	@ApiResponses({ @ApiResponse(code = 200, response = UserActivityAttendList.class, message = "活动报名信息列表") })
	@GetMapping(value = "/attend/ofactivity", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findAcivityAttendDetail(
			@RequestParam(value = "activityId", required = true) String activityId) {

		List<ActivityAttendentEntity> activityAttendList = activityAttendSer.findActivityAttendByAct(activityId);
		List<ActivityAttendVo> activityAttendVoList = new ArrayList<>();
		Long attendNums = 0L;
		if (activityAttendList != null) {
			ActivityAttendVo activityAttendVo = null;

			for (ActivityAttendentEntity activitAttend : activityAttendList) {
				activityAttendVo = new ActivityAttendVo();
				attendNums = attendNums + activitAttend.getUserCount();
				BeanUtils.copyProperties(activitAttend, activityAttendVo);
				activityAttendVoList.add(activityAttendVo);

			}
		} else {
			LOG.error("查询结果为空！");
		}
		// 这里的报名总数就放在total里了这里就不做分页了
		return UserActivityAttendList.listAndCount(activityAttendVoList, attendNums);

	}

	// 下为B端管理接口

	@ApiOperation(value = "获取商家活动列表", notes = "获取商家活动列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityListOrgnizer.class, message = "获取商家活动列表") })
	@GetMapping(value = "/oforgnizer", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> contentList(
			@RequestParam(value = "title", required = false)@ApiParam(value="活动名称",required = false) String title,
			@RequestParam(value = "pubStart", required = false) Long pubStart,
			@RequestParam(value = "pubEnd", required = false) Long pubEnd,
			@RequestParam(value = "authStatus", required = false)@ApiParam(value="10未审核，20审核成功", required = false)String authStatus,
			@ModelAttribute(value = "pvo") PagingVo pvo,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String orgnizerId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		
		List<ActivityEntity> activityList = activitySer.findActivityListByOrgnizer(orgnizerId, title, pubStart, pubEnd,
				authStatus,pvo);
		List<ActivityVo> activityVoList = new ArrayList<>();
		ActivityVo activityVo = null;
		if (StringUtils.isNotEmpty(orgnizerId)) {
			if (activityList != null) {
				for (ActivityEntity activity : activityList) {
					activityVo = new ActivityVo();
					BeanUtils.copyProperties(activity, activityVo);
					List<ActivityAttendentEntity> activityAttendList = activityAttendSer
							.findActivityAttendByAct(activity.getId());
					Long attendNums = 0L;
					if (activityAttendList != null) {
						for (ActivityAttendentEntity activityAttend : activityAttendList) {
							attendNums = attendNums + activityAttend.getUserCount();
						}
					}

					activityVo.setAttendNums(attendNums);
					activityVoList.add(activityVo);
				}

			}
			return ActivityListOrgnizer.listAndCount(activityVoList, (Long) pvo.getTc());
		}
		return GenericResponse.ng("活动列表查询出错！");

	}

	@ApiOperation(value = "编辑活动", notes = "编辑活动")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "编辑活动") })
	@PutMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> editActivity(@RequestBody ActivityVo activityVo) {
		if (activityVo != null) {
			ActivityEntity activity = new ActivityEntity();
			BeanUtils.copyProperties(activityVo, activity);
			boolean result = activitySer.updateActivity(activity);
			if (result) {
				return GenericResponse.ok();
			}
		}
		return GenericResponse.ng("修改失败请重新尝试！");

	}

	@ApiOperation(value = "使活动结束", notes = "使活动结束")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "使活动结束") })
	@PutMapping(value = "/{id}/status:stop", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> invalActivity(@PathVariable(value = "id", required = true) String id) {
		boolean result = activitySer.updateActivityStatus(id);
		if (result) {
			return GenericListResponse.ok();
		}
		return GenericListResponse.ng("是活动结束失败,请重新尝试！");

	}

	@ApiOperation(value = "删除活动", notes = "删除活动")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "根据活动Id删除活动") })
	@DeleteMapping(value = "/{id}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> deleteActivity(@PathVariable(value = "id", required = true) String id) {
		boolean result = activitySer.delActivity(id);
		if (result) {
			return GenericResponse.ok();
		}
		return GenericResponse.ng("删除失败！");
	}

	@ApiOperation(value = "添加活动", notes = "添加活动")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityPubResponse.class, message = "添加活动") })
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> createActivity(@RequestBody ActivityVo activityVo,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		activityVo.setOrgnizerId(shopId);
		SitesInfo4Activity sitesInfo = sitesApi.getSitesInfo4Activity(shopId);
		ActivityEntity activity = null;
		activity = new ActivityEntity();
		BeanUtils.copyProperties(activityVo, activity);
		activity.setId(idGenerator.nextId());
		activity.setStatus("1");
		activity.setAuthStatus("10");
		activity.setShareNum(0);
		activity.setLatitude(sitesInfo.getCenterLatitude());
		activity.setLongitude(sitesInfo.getCenterLongitude());
		activity.setZoneProvince(sitesInfo.getZoneProvince());
		activity.setZoneCity(sitesInfo.getZoneCity());
		activity.setZoneDistrict(sitesInfo.getZoneDistrict());
		activity.setOrgnizerImgUrl(sitesInfo.getLogo());
		activity.setOrgnizerInfo(sitesInfo.getIntroduction());
		activity.setOrgnizerType("10");
		activity.setOrgnizerName(sitesInfo.getName());
		activity.setPubTime(System.currentTimeMillis());
		activity.setManagerId(userId);
		boolean result = activitySer.addActivity(activity);
		try {
			submitVarify(activity);
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
		}
		
		if (result) {
			return GenericResponse.ok();
		} else {
			return GenericResponse.ng("活动发送失败！");
		}

	}
	
	@Async
	public boolean submitVarify(ActivityEntity activity){
		
		Map<String, Object> body = MapUtil.buildMapKVGen(
				new Object[][] { { "title", activity.getTitle() },
					{ "content", activity.getContent() },
					{ "startTime", activity.getStartTime() },
					{ "endTime", activity.getEndTime() },
					{ "memo", activity.getMemo() },
					{ "postUrl", activity.getPostUrl() },
					{ "zoneProvince", activity.getZoneProvince() },
					{ "zoneCity", activity.getZoneCity() },
					{ "zoneDistrict", activity.getZoneDistrict() },
					{ "orgnizerId", activity.getOrgnizerId() },
					{ "orgnizerName", activity.getOrgnizerName() },
					{ "orgnizerInfo", activity.getOrgnizerInfo() },
					{ "orgnizerType", activity.getOrgnizerType() },
					{ "orgnizerUrl", activity.getOrgnizerImgUrl() },
					{ "postUrl", activity.getPostUrl() },
					{ "price", activity.getPrice() },
					{ "pubTime", activity.getPubTime() },
					{ "contact", activity.getContact() },
					{ "maxParticipants", activity.getMaxParticipants() },
					{ "minParticipants", activity.getMinParticipants() },
					{ "address", activity.getAddress() },
					{ "longitude", activity.getLongitude() },
					{ "latitude", activity.getLatitude() },
					{ "status", activity.getStatus() },
					{ "authStatus", activity.getAuthStatus() },
					{ "status", activity.getStatus() },
					{ "managerId", activity.getManagerId() },
					{ "attendMethod", activity.getAttendMethod() },
					{ "formerId", activity.getId()},
					
				
				}, String.class,
				Object.class);
		String respStr = post(yunyingAdress+"/admin/xqActivity", body);
		LOG.info(respStr);
//		ContentStaticResponseVo contentStaticVo = JsonUtil.asObject(respStr, ContentStaticResponseVo.class);
		return true;
		
	}
	
	private String post(String url, Map<String, Object> body) {
		HttpEntity<Map<String, Object>> reqEntity = new HttpEntity<>(body);
		String respStr = null;
		try {
			respStr = rest.postForObject(new URI(url), reqEntity, String.class);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return respStr;
	}

	@ApiOperation(value = "获取活动详情（B端管理用）", notes = "获取活动详情（B端管理用）")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityDetailResponse.class, message = "获取活动详情") })
	@GetMapping(value = "/{id}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findActivityDetail4B(@PathVariable(value = "id", required = true) String id) {
		ActivityEntity activity = activitySer.findActivity(id);
		if (activity != null) {
			ActivityVo activityVo = new ActivityVo();
			BeanUtils.copyProperties(activity, activityVo);
			List<ActivityAttendentEntity> activityAttendList = activityAttendSer
					.findActivityAttendByAct(activity.getId());
			Long attendNums = 0L;
			if (activityAttendList != null) {
				for (ActivityAttendentEntity activityAttend : activityAttendList) {
					attendNums = attendNums + activityAttend.getUserCount();
				}
			}

			activityVo.setAttendNums(attendNums);
			return ActivityDetailResponse.okWithData(activityVo);
		}
		LOG.debug("查询结果为空！");
		return GenericResponse.ng("查询该活动失败！");
	}


	@ApiOperation(value = "根据活动标题-获取商家活动列表", notes = "根据活动标题-获取商家活动列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityListOrgnizer.class, message = "根据活动标题-获取商家活动列表") })
	@GetMapping(value = "/search", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> contentList(
			@RequestParam(value = "title", required = false)@ApiParam(value="活动名称",required = false) String title,
			@ApiParam(value="页码,从1开始", required=false) @RequestParam(defaultValue = "1") int pn,
			@ApiParam(value="条数", required=false) @RequestParam(defaultValue = "10") int ps,
			HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String orgnizerId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
//		String orgnizerId = "sites001";
		PagingVo pagingVo = new PagingVo(pn-1, ps);

		List<ActivityEntity> activityList = activitySer.findActivityFromEsByTitle(orgnizerId, title, pagingVo);
		List<ActivityVo> activityVoList = new ArrayList<>();
		ActivityVo activityVo = null;
		if (StringUtils.isNotEmpty(orgnizerId)) {
			if (activityList != null) {
				for (ActivityEntity activity : activityList) {
					activityVo = new ActivityVo();
					BeanUtils.copyProperties(activity, activityVo);
					activityVoList.add(activityVo);
				}
			}
			return ActivityListOrgnizer.listNoCount(activityVoList);
		}
		return GenericResponse.ng("活动列表查询出错！");

	}
	
	@ApiOperation(value = "对接运营后台活动的审核", notes = "对接运营后台活动的审核")
	@ApiResponses({ @ApiResponse(code = 200, response = ActivityListOrgnizer.class, message = "对接运营后台活动的审核") })
	@PutMapping(value = "/opr_back", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> verifyActivity(@RequestParam(value="activityId",required=true)@ApiParam(value="活动Id",required=true)String activityId,@RequestParam(value="authStatus",required=true)@ApiParam(value="20审核成功，30审核失败",required=true)String authStatus){
		ActivityEntity activity = activitySer.findActivity(activityId);
		activity.setAuthStatus(authStatus);
		activitySer.addActivity(activity);
		return GenericResponse.ok();
		
	}

}
